package bsts.view.subscription;

// updated

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

import bsts.application.BSTSApplication;
import bsts.model.Account;
import bsts.model.AccountStatus;
import bsts.model.DigitalVoice;
import bsts.model.MobileVoice;
import bsts.model.Customer;
import bsts.model.Feature;
import bsts.model.Plan;
import bsts.model.Subscription;
import bsts.model.SubscriptionStatus;

public class UpdSubscriptionPanel extends JPanel {

	private static final long serialVersionUID = 1L;

	private JFrame containerParent;
	private JFrame container;
	private BSTSApplication manager;
	private Customer customer;
	private Account account;

	private JPanel pnlMain;
	private JPanel pnlBasicInfo;
	private JPanel pnlCustomer;
	private JPanel pnlAccount;
	private JPanel pnlSubscription;
	private JPanel pnlFeatures;
	private JPanel pnlFeaturesBtns;
	private JPanel pnlButtons;

	// customer info
	private JLabel lblName;

	private JLabel lblName_data;

	// account info
	private JLabel lblAccountNo;
	private JLabel lblAccountStatus;

	private JLabel lblAccountNo_data;
	private JLabel lblAccountStatus_data;

	// subscription info
	private JLabel lblPlanId;
	private JLabel lblPlanName;
	private JLabel lblPhoneNo;
	private JLabel lblDateCommenced;
	private JLabel lblDateTerminated;
	private JLabel lblSubscriptionStatus;

	private JComboBox cbxPlanName_data;
	private JLabel lblPlanName_data;
	private JLabel lblPhoneNo_data;
	private JLabel lblDateCommenced_data;
	private JLabel lblDateTerminated_data;
	private JLabel lblSubscriptionStatus_data;

	// feature
	private JTable tblFeatures;
	private JScrollPane scrFeatures;

	private JButton btnAddFeature;
	private JButton btnTerminateFeature;
	private JButton btnTerminateSubscription;
	private JButton btnBack;

	private ActionListener actlis_cbxPlanName_data;
	private ActionListener actlis_btnAddFeature;
	private ActionListener actlis_btnTerminateFeature;
	private ActionListener actlis_btnTerminateSubscription;
	private ActionListener actlis_btnBack;

	private ArrayList<Feature> selectedFeatures = new ArrayList<Feature>();
	private ArrayList<Subscription> subscriptions = new ArrayList<Subscription>();

	public UpdSubscriptionPanel(JFrame containerParent, JFrame container,
			BSTSApplication manager, Account account, Customer customer) {
		this.containerParent = containerParent;
		this.container = container;
		this.manager = manager;
		this.account = account;
		this.customer = customer;

		pnlMain = new JPanel();
		pnlBasicInfo = new JPanel();
		pnlCustomer = new JPanel();
		pnlAccount = new JPanel();
		pnlSubscription = new JPanel();
		pnlFeatures = new JPanel();
		pnlFeaturesBtns = new JPanel();
		pnlButtons = new JPanel();

		pnlMain.setLayout(new BorderLayout());
		pnlBasicInfo.setLayout(new BoxLayout(pnlBasicInfo, BoxLayout.Y_AXIS));
		pnlCustomer.setLayout(new GridLayout(1, 2));
		pnlAccount.setLayout(new GridLayout(2, 2));
		pnlSubscription.setLayout(new GridLayout(6, 2));
		pnlFeatures.setLayout(new BoxLayout(pnlFeatures, BoxLayout.Y_AXIS));
		pnlFeaturesBtns.setLayout(new FlowLayout(FlowLayout.RIGHT));
		pnlButtons.setLayout(new FlowLayout(FlowLayout.RIGHT));

		pnlCustomer.setBorder(BorderFactory.createTitledBorder("Customer"));
		pnlAccount.setBorder(BorderFactory.createTitledBorder("Account"));
		pnlSubscription.setBorder(BorderFactory
				.createTitledBorder("Subscription"));
		pnlFeatures.setBorder(BorderFactory.createTitledBorder("Feature"));

		lblName = new JLabel("Name:");
		lblAccountNo = new JLabel("Account No.:");
		lblAccountStatus = new JLabel("Account Status:");
		lblPlanId = new JLabel("Subscribe Plan:");
		lblPlanName = new JLabel("Plan:");
		lblPhoneNo = new JLabel("Phone No.:");
		lblDateCommenced = new JLabel("Commenced Date:");
		lblDateTerminated = new JLabel("Terminated Date:");
		lblSubscriptionStatus = new JLabel("Subscription Status:");

		lblName_data = new JLabel(customer.getFullname());
		lblAccountNo_data = new JLabel(account.getAccountNo());
		lblAccountStatus_data = new JLabel(account.getAccountStatus()
				.toString());
		lblPhoneNo_data = new JLabel();
		lblDateCommenced_data = new JLabel();
		lblDateTerminated_data = new JLabel();
		lblSubscriptionStatus_data = new JLabel();

		subscriptions = account.getSubscriptions();

		cbxPlanName_data = new JComboBox();
		lblPlanName_data = new JLabel(
				(subscriptions.size() > 0) ? subscriptions.get(0).getPlan()
						.getName() : "-");

		for (Subscription subscription : subscriptions)
			cbxPlanName_data.addItem(subscription.getSubscriptionId());

		if ((subscriptions.size() > 0)) {
			Plan tempPlan = subscriptions.get(0).getPlan();

			if (tempPlan instanceof DigitalVoice) {
				lblPhoneNo_data.setText(((DigitalVoice) tempPlan).getPhoneNo());
			} else if (tempPlan instanceof MobileVoice) {
				lblPhoneNo_data.setText(((MobileVoice) tempPlan).getPhoneNo());
			} else {
				lblPhoneNo_data.setText("N.A");
			}
		}
		
		lblDateCommenced_data
				.setText((subscriptions.size() > 0) ? subscriptions.get(0)
						.getStrDateCommenced() : "-");
		lblDateTerminated_data
				.setText((subscriptions.size() > 0) ? subscriptions.get(0)
						.getStrDateTerminated() : "-");
		lblSubscriptionStatus_data
				.setText((subscriptions.size() > 0) ? subscriptions.get(0)
						.getSubscriptionStatus().toString() : "-");

		lblSubscriptionStatus_data.setPreferredSize(new Dimension(150,
				lblSubscriptionStatus_data.getHeight()));

		tblFeatures = new JTable();
		scrFeatures = new JScrollPane();

		if (subscriptions.size() > 0)
			selectedFeatures = subscriptions.get(0).getPlan().getFeatures();

		initTbl();
		scrFeatures
				.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		scrFeatures.add(tblFeatures, null);
		scrFeatures.setViewportView(tblFeatures);
		scrFeatures.setPreferredSize(new Dimension(575, 250));

		btnAddFeature = new JButton("Add Feature");
		btnTerminateFeature = new JButton("Terminate Feature");
		btnTerminateSubscription = new JButton("Terminate Subscription");
		btnBack = new JButton("Back");

		pnlCustomer.add(lblName);
		pnlCustomer.add(lblName_data);

		pnlAccount.add(lblAccountNo);
		pnlAccount.add(lblAccountNo_data);
		pnlAccount.add(lblAccountStatus);
		pnlAccount.add(lblAccountStatus_data);

		pnlSubscription.add(lblPlanId);
		pnlSubscription.add(cbxPlanName_data);
		pnlSubscription.add(lblPlanName);
		pnlSubscription.add(lblPlanName_data);
		pnlSubscription.add(lblPhoneNo);
		pnlSubscription.add(lblPhoneNo_data);
		pnlSubscription.add(lblDateCommenced);
		pnlSubscription.add(lblDateCommenced_data);
		pnlSubscription.add(lblDateTerminated);
		pnlSubscription.add(lblDateTerminated_data);
		pnlSubscription.add(lblSubscriptionStatus);
		pnlSubscription.add(lblSubscriptionStatus_data);

		pnlFeaturesBtns.add(btnAddFeature);
		pnlFeaturesBtns.add(btnTerminateFeature);

		pnlFeatures.add(scrFeatures);
		pnlFeatures.add(pnlFeaturesBtns);

		pnlButtons.add(btnTerminateSubscription);
		pnlButtons.add(btnBack);

		pnlBasicInfo.add(pnlCustomer);
		pnlBasicInfo.add(pnlAccount);
		pnlBasicInfo.add(pnlSubscription);

		pnlMain.add(pnlBasicInfo, BorderLayout.WEST);
		pnlMain.add(pnlFeatures, BorderLayout.EAST);
		pnlMain.add(pnlButtons, BorderLayout.SOUTH);

		this.add(pnlMain);

		initActionListener();
		setBtnFuncs(account.getAccountStatus());
		if (subscriptions.size() > 0) {
			setBtnFuncs(subscriptions.get(0).getSubscriptionStatus());
		} else {
			enableDisableBtnFuncs(false);
		}
	}

	public void refresh(ArrayList<Feature> selectedFeatures) {
		this.selectedFeatures = selectedFeatures;
		refreshTbl();

		this.revalidate();
		this.repaint();
	}

	public void refreshTbl() {
		tblFeatures.revalidate();
		tblFeatures.repaint();
	}

	private void enableDisableBtnFuncs(boolean enable) {
		if (enable) {
			btnAddFeature.setEnabled(true);
			btnTerminateFeature.setEnabled(true);
			btnTerminateSubscription.setEnabled(true);
		} else {
			btnAddFeature.setEnabled(false);
			btnTerminateFeature.setEnabled(false);
			btnTerminateSubscription.setEnabled(false);
		}
	}

	private void setBtnFuncs(AccountStatus accountStatus) {
		if (accountStatus.equals(AccountStatus.Activated)) {
			enableDisableBtnFuncs(true);
		} else {
			enableDisableBtnFuncs(false);
		}
	}

	private void setBtnFuncs(SubscriptionStatus subscriptionStatus) {
		if (account.getAccountStatus().equals(AccountStatus.Activated)) {
			if (subscriptionStatus.equals(SubscriptionStatus.Activated)) {
				enableDisableBtnFuncs(true);
			} else {
				enableDisableBtnFuncs(false);
			}
		}
	}

	private void initTbl() {
		final String[] strHeaded = { "Name", "Rate", "Type", "Status",
				"Date Commenced", "Date Terminated" };

		// Create a model of the data.
		TableModel dataModel = new AbstractTableModel() {
			private static final long serialVersionUID = 1L;

			public int getColumnCount() {
				return strHeaded.length;
			}

			public int getRowCount() {
				return selectedFeatures.size();
			}

			public Object getValueAt(int row, int col) {
				Feature feature = selectedFeatures.get(row);

				if (col == 0) {
					return feature.getName();
				} else if (col == 1) {
					return feature.getRate();
				} else if (col == 2) {
					return feature.getRateType().toString();
				} else if (col == 3) {
					return feature.getSubscriptionStatus().toString();
				} else if (col == 4) {
					return feature.getStrDateCommenced();
				} else if (col == 5) {
					return feature.getStrDateTerminated();
				} else {
					return null;
				}
			}

			public String getColumnName(int column) {
				return strHeaded[column];
			}

			public Class<?> getColumnClass(int col) {
				return getValueAt(0, col).getClass();
			}
		};

		tblFeatures = new JTable(dataModel);
		tblFeatures.getSelectionModel();
		tblFeatures.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

		DefaultTableCellRenderer right = new DefaultTableCellRenderer();
		right.setHorizontalAlignment(DefaultTableCellRenderer.TRAILING);

		tblFeatures.setDefaultRenderer(Object.class, right);

		int[] intWidth = { 130, 50, 75, 70, 125, 125 };

		for (int i = 0; i < intWidth.length; i++) {
			TableColumn tblCol = tblFeatures.getColumn(strHeaded[i]);
			tblCol.setMaxWidth(intWidth[i]);
		}
	}

	private void initActionListener() {
		actlis_cbxPlanName_data = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int index = cbxPlanName_data.getSelectedIndex();
				Subscription selectedSubscription = subscriptions.get(index);
				
				if (selectedSubscription.getPlan() instanceof DigitalVoice) {
					lblPhoneNo_data.setText(((DigitalVoice) selectedSubscription.getPlan()).getPhoneNo());
				} else if (selectedSubscription.getPlan() instanceof MobileVoice) {
					lblPhoneNo_data.setText(((MobileVoice) selectedSubscription.getPlan()).getPhoneNo());
				} else {
					lblPhoneNo_data.setText("N.A");
				}

				lblPlanName_data.setText(selectedSubscription.getPlan()
						.getName());
				lblDateCommenced_data.setText(selectedSubscription
						.getStrDateCommenced());
				lblDateTerminated_data.setText(selectedSubscription
						.getStrDateTerminated());
				lblSubscriptionStatus_data.setText(selectedSubscription
						.getSubscriptionStatus().toString());

				selectedFeatures = selectedSubscription.getPlan().getFeatures();
				refreshTbl();

				setBtnFuncs(selectedSubscription.getSubscriptionStatus());

				pnlMain.revalidate();
				pnlMain.repaint();
			}
		};

		actlis_btnAddFeature = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int index = cbxPlanName_data.getSelectedIndex();

				Plan plan = manager.getSubscriptionManager().getDefaultPlan(
						subscriptions.get(index).getPlan().getPlanId());
				ArrayList<Feature> availableFeatures = plan.getFeaturesClone();
				selectedFeatures = subscriptions.get(index).getPlan()
						.getFeatures();

				manager.getViewManager().showUpdSubAddFeatureWindow(container,
						availableFeatures, selectedFeatures,
						subscriptions.get(index), account, customer);
			}
		};

		actlis_btnTerminateFeature = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (tblFeatures.getSelectedRow() >= 0) {
					if (selectedFeatures.get(tblFeatures.getSelectedRow())
							.getSubscriptionStatus().equals(
									SubscriptionStatus.Activated)) {
						if (JOptionPane.showConfirmDialog(container,
								"Confirm to deactivate selected feature?") == JOptionPane.YES_OPTION) {
							selectedFeatures.get(tblFeatures.getSelectedRow())
									.setSubscriptionStatus(
											SubscriptionStatus.Terminated);
							subscriptions.get(
									cbxPlanName_data.getSelectedIndex())
									.getPlan().setFeatures(selectedFeatures);
							account.addSubscription(subscriptions
									.get(cbxPlanName_data.getSelectedIndex()));
							customer.putAccount(account);
							manager.getCustomerManager().updateCustomer(
									customer);
							refreshTbl();
						}
					} else {
						JOptionPane.showMessageDialog(container,
								"Feature had been deactivated.");
					}
				}
			}
		};

		actlis_btnTerminateSubscription = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (cbxPlanName_data.getSelectedIndex() >= 0) {
					if (subscriptions.get(cbxPlanName_data.getSelectedIndex())
							.getSubscriptionStatus().equals(
									SubscriptionStatus.Activated)) {
						if (JOptionPane
								.showConfirmDialog(container,
										"Confirm to terminate selected subscription plan?") == JOptionPane.YES_OPTION) {
							subscriptions.get(
									cbxPlanName_data.getSelectedIndex())
									.setSubscriptionStatus(
											SubscriptionStatus.Terminated);
							account.addSubscription(subscriptions
									.get(cbxPlanName_data.getSelectedIndex()));
							customer.putAccount(account);
							manager.getCustomerManager().updateCustomer(
									customer);
							refreshTbl();

							lblDateTerminated_data.setText((subscriptions
									.get(cbxPlanName_data.getSelectedIndex())
									.getStrDateTerminated()));

							lblSubscriptionStatus_data.setText(subscriptions
									.get(cbxPlanName_data.getSelectedIndex())
									.getSubscriptionStatus().toString());
							
							enableDisableBtnFuncs(false);

							pnlMain.revalidate();
							pnlMain.repaint();
						}
					} else {
						JOptionPane.showMessageDialog(container,
								"Subscription plan had been terminated.");
					}
				}
			}
		};

		actlis_btnBack = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				manager.getViewManager().goBackParent(containerParent,
						container);
			}
		};

		cbxPlanName_data.addActionListener(actlis_cbxPlanName_data);
		btnAddFeature.addActionListener(actlis_btnAddFeature);
		btnTerminateFeature.addActionListener(actlis_btnTerminateFeature);
		btnTerminateSubscription
				.addActionListener(actlis_btnTerminateSubscription);
		btnBack.addActionListener(actlis_btnBack);
	}
}
